package com.sline.day03._03_smis.dao.impl;

import com.sline.day03._03_smis.dao.IStudentDao;
import com.sline.day03._03_smis.domain.Student;
import com.sline.day03._03_smis.template.JdbcTemplate;
import com.sline.day03._03_smis.template.ResultSetHandler;
import com.sline.day03._03_smis.template.handler.BeanHandler;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements IStudentDao {
    @Override
    public void save(Student student) {
        String sql = "insert into t_student (name, age) values (?, ?)";

        int row = JdbcTemplate.update(sql, student.getName(), student.getAge());
        System.out.println("成功操作" + row + "行");

    }

    @Override
    public void delete(Long id) {
        String sql = "delete from t_student where id = ?";

        int row = JdbcTemplate.update(sql, id);
        System.out.println("成功操作" + row + "行");
    }

    @Override
    public void update(Long id, Student student) {
        String sql = "update t_student set name = ?, age = ? where id = ?";
        int row = JdbcTemplate.update(sql, student.getName(), student.getAge(), id);
        System.out.println("成功操作" + row + "行");
    }

    @Override
    public Student get(Long id) {

        String sql = "select * from t_student where id = ?";

        List<Student> arr = JdbcTemplate.query(sql, new StudentResultSetHandle(), id);

        return JdbcTemplate.query(sql, new BeanHandler<>(Student.class), id);
    }

    @Override
    public List<Student> list() {
        String sql = "select * from t_student";

        return JdbcTemplate.query(sql, new StudentResultSetHandle());
    }

    class StudentResultSetHandle implements ResultSetHandler<List<Student>> {
        @Override
        public List<Student> handle(ResultSet resultSet) {
            List<Student> arr = new ArrayList<>();
            try {
                while (resultSet.next()) {
                    Student student = new Student();

                    student.id = resultSet.getLong("id");
                    student.name = resultSet.getString("name");
                    student.age = resultSet.getInt("age");

                    arr.add(student);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return arr;
        }
    }
}
